package com.it.zhangjun.arithmetic.回溯;

/**
 * @author jun.zhang6
 * @date 2020/10/27
 */
public class Queues2 {
    public static void main(String[] args) {
        Queues2 queues2 = new Queues2();
        queues2.putQueues(4);
    }

    private int[] queues;

    private int ways;

    private void putQueues(int count) {
        if (count < 1) {
            return;
        }
        queues = new int[count];

        place(0);
    }

    private void place(int row) {
        if (row == queues.length) {
            ways++;
            show();
            return;
        }
        for (int col = 0; col < queues.length; col++) {
            if (isValid(row, col)) {
                queues[row] = col;
                place(row + 1);
            }
        }
    }

    private boolean isValid(int row, int col) {
        for (int i = 0; i < row; i++) {
            if (col == queues[i]) {
                return false;
            }
            if (row - i == Math.abs(col - queues[i])) {
                return false;
            }
        }
        return true;
    }

    /**
     * 显示皇后的摆放情况
     */
    private void show() {
        for (int row = 0; row < queues.length; row++) {
            for (int col = 0; col < queues.length; col++) {
                if (queues[row] == col) {
                    System.out.print(1);
                } else {
                    System.out.print(0);
                }
                System.out.print(" ");
            }
            System.out.println();
        }
        System.out.println("-----------------------------------");
    }

}
